package stone926.mods.more_enchantments.enchantments;

import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnchantmentTarget;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EquipmentSlot;
import net.minecraft.entity.LivingEntity;
import net.minecraft.item.AxeItem;
import net.minecraft.item.ItemStack;
import net.minecraft.particle.ParticleTypes;
import net.minecraft.predicate.entity.EntityPredicates;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.math.Box;
import stone926.mods.more_enchantments.interfaces.ILivingEntity;
import stone926.mods.more_enchantments.util.RandomUtil;

public class TpSuppressionEnchantment extends Enchantment {

  public TpSuppressionEnchantment() {
    super(Rarity.COMMON, EnchantmentTarget.WEAPON, new EquipmentSlot[]{EquipmentSlot.MAINHAND});
  }

  public static int getSuppressionTicks(int lvl) {
    return lvl * 8 * 20;
  }

  public static double getAroundSuppressionChance(int lvl) {
    return Math.min(1, lvl * 0.15);
  }

  @Override
  public int getMaxLevel() {
    return 3;
  }

  @Override
  public boolean isAcceptableItem(ItemStack stack) {
    return super.isAcceptableItem(stack) || stack.getItem() instanceof AxeItem;
  }

  @Override
  public void onTargetDamaged(LivingEntity user, Entity target, int level) {
    super.onTargetDamaged(user, target, level);
    if (target instanceof LivingEntity l && ((ILivingEntity) l).getTpSuppression() <= 0) {
      ((ILivingEntity) l).setTpSuppression(getSuppressionTicks(level));
    }
    RandomUtil.runIfPossible(getAroundSuppressionChance(level), user.getRandom(), () -> user.world
      .getEntitiesByClass(
        LivingEntity.class,
        Box.from(target.getPos()).expand(getRadius(level)),
        EntityPredicates.VALID_ENTITY
      )
      .stream().filter(e -> e != target && e != user)
      .forEach(livingEntity -> {
        if (((ILivingEntity) livingEntity).getTpSuppression() <= 0) {
          ((ILivingEntity) livingEntity).setTpSuppression(TpSuppressionEnchantment.getSuppressionTicks(level) / 2);
        }
        if (user.getEntityWorld() instanceof ServerWorld server) {
          server.spawnParticles(
            ParticleTypes.CRIT,
            livingEntity.getX(), livingEntity.getY() + livingEntity.getEyeHeight(livingEntity.getPose()), livingEntity.getZ(),
            RandomUtil.nextInt(20, 40, user.getRandom()), 0.25, 0.25, 0.25, 0
          );
        }
      })
    );
  }

  private int getRadius(int level) {
    return level * 7;
  }

}
